package comtgl.demo.test;

import java.util.Date;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        // 创建限流服务，每秒50次，每分钟1000次
        RateLimitService rateLimitService = new TokenBucketRateLimitServiceImpl(50, 1000);

        // 测试1：连续请求200次
        System.out.println("测试连续请求200次：");
        testRequests(rateLimitService, 200);

        // 等待1秒
        Thread.sleep(1000);

        // 测试2：每秒请求60次，持续3秒
        System.out.println("\n测试每秒请求60次，持续3秒：");
//        for (int i = 0; i < 3; i++) {
//            testRequests(rateLimitService, 60);
//            Thread.sleep(1000);
//        }
    }

    private static void testRequests(RateLimitService rateLimitService, int count) throws InterruptedException {
        int success = 0;
        int blocked = 0;

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            if (rateLimitService.tryAccess("test")) {
                success++;
            } else {
                blocked++;
//                Thread.sleep(100);
                System.out.println(new Date() + "请求被限流：" + i);
            }
        }
        long elapsed = System.currentTimeMillis() - startTime;

        System.out.printf("请求总数: %d, 成功: %d, 被限流: %d, 耗时: %dms%n",
                count, success, blocked, elapsed);
    }
}
